# admin_department_routes.py
from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from datetime import timedelta, datetime
from sqlalchemy import func
from inc.models import AdminDepartment, AdminMember, OperationLog, db
from .admin_class import DepartmentForm

admin_department_bp = Blueprint('admin_department', __name__)

@admin_department_bp.route('/departments')
@login_required
def department_management():
    # 获取所有部门并按排序号排序
    all_departments = AdminDepartment.query.order_by(AdminDepartment.order_num).all()
    total_departments = len(all_departments)
    top_level_departments = [dept for dept in all_departments if dept.parent_id is None]
    top_level_count = len(top_level_departments)
    total_members = AdminMember.query.count()

    # 获取最后更新时间并格式化
    latest_update = db.session.query(func.max(AdminDepartment.update_time)).scalar()
    if latest_update:
        now = datetime.now()
        if latest_update.date() == now.date():
            last_update_str = "今天"
        elif latest_update.date() == now.date() - timedelta(days=1):
            last_update_str = "昨天"
        else:
            days_diff = (now.date() - latest_update.date()).days
            last_update_str = f"{days_diff}天前"
    else:
        last_update_str = "无记录"

    # 构建部门树形结构
    def build_department_tree(departments, parent_id=None, level=0, path="", max_level=5):
        if level >= max_level:
            return []

        tree = []
        for dept in departments:
            if dept.parent_id == parent_id:
                current_path = f"{path}/{dept.name}" if path else dept.name
                children = build_department_tree(departments, dept.id, level + 1, current_path, max_level)

                dept_dict = {
                    'id': dept.id,
                    'name': dept.name,
                    'parent_id': dept.parent_id,
                    'order_num': dept.order_num,
                    'wecom_id': dept.wecom_id,
                    'level': level,
                    'children': children,
                    'member_count': len(dept.members),
                    'path': current_path
                }
                tree.append(dept_dict)
        return tree

    department_tree = build_department_tree(all_departments)

    return render_template('admin/admin/admin_department.html',
                           department_tree=department_tree,
                           stats={
                               'total_departments': total_departments,
                               'total_members': total_members,
                               'top_level_count': top_level_count,
                               'last_update': last_update_str
                           })

@admin_department_bp.route('/departments/add', methods=['GET', 'POST'])
@login_required
def add_department():
    form = DepartmentForm()
    form.parent_id.choices = [(0, '-- 顶级部门 --')]
    all_departments = AdminDepartment.query.order_by(AdminDepartment.order_num).all()

    # 构建部门选项（带树形结构）
    def build_department_options(departments, parent_id=None, level=0, exclude_id=None):
        options = []
        children = [dept for dept in departments
                    if dept.parent_id == parent_id and dept.id != exclude_id]
        children.sort(key=lambda x: x.order_num)

        for i, dept in enumerate(children):
            # 构建树形前缀
            if level == 0:
                prefix = ""
            elif i == len(children) - 1:  # 最后一个子节点
                prefix = "    " * (level - 1) + "└── "
            else:
                prefix = "    " * (level - 1) + "├── "

            # 添加深度指示器
            depth_indicator = "• " * level
            display_name = f"{prefix}{depth_indicator}{dept.name}"

            # 添加成员计数
            if dept.members:
                display_name += f" ({len(dept.members)})"

            options.append((dept.id, display_name))
            options.extend(build_department_options(
                departments, dept.id, level + 1, exclude_id
            ))
        return options

    form.parent_id.choices.extend(build_department_options(all_departments))

    if form.validate_on_submit():
        try:
            # 检查部门名称唯一性
            existing_department = AdminDepartment.query.filter(
                AdminDepartment.name == form.name.data
            ).first()

            if existing_department:
                flash('部门名称已存在', 'danger')
                return render_template('admin/admin/admin_department_form.html', form=form)

            department = AdminDepartment(
                name=form.name.data,
                parent_id=form.parent_id.data if form.parent_id.data != 0 else None,
                order_num=form.order_num.data,
                wecom_id=form.wecom_id.data
            )
            db.session.add(department)

            log = OperationLog(
                admin_id=current_user.id,
                action="添加部门",
                resource="AdminDepartment",
                details=f"添加部门: {form.name.data}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.add(log)
            db.session.commit()

            flash('部门已添加', 'success')
            return redirect(url_for('admin.admin_department.department_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'添加部门时出错: {str(e)}', 'danger')

    return render_template('admin/admin/admin_department_form.html',
                           form=form,
                           title='添加部门',
                           all_departments=all_departments)

@admin_department_bp.route('/departments/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_department(id):
    department = AdminDepartment.query.get_or_404(id)
    form = DepartmentForm(obj=department)
    form.parent_id.choices = [(0, '-- 顶级部门 --')]
    all_departments = AdminDepartment.query.order_by(AdminDepartment.order_num).all()

    # 构建部门选项（带树形结构）
    def build_department_options(departments, parent_id=None, level=0, exclude_id=None):
        options = []
        children = [dept for dept in departments
                    if dept.parent_id == parent_id and dept.id != exclude_id]
        children.sort(key=lambda x: x.order_num)

        for i, dept in enumerate(children):
            # 构建树形前缀
            if level == 0:
                prefix = ""
            elif i == len(children) - 1:  # 最后一个子节点
                prefix = "    " * (level - 1) + "└── "
            else:
                prefix = "    " * (level - 1) + "├── "

            # 添加深度指示器
            depth_indicator = "• " * level
            display_name = f"{prefix}{depth_indicator}{dept.name}"

            # 添加成员计数
            if dept.members:
                display_name += f" ({len(dept.members)})"

            options.append((dept.id, display_name))
            options.extend(build_department_options(
                departments, dept.id, level + 1, exclude_id
            ))
        return options

    form.parent_id.choices.extend(build_department_options(all_departments, exclude_id=id))

    if form.validate_on_submit():
        try:
            # 检查循环依赖
            if form.parent_id.data != 0:
                parent_id = form.parent_id.data

                # 检查新父部门是否是当前部门的子部门
                def is_child_department(parent_id, current_id):
                    parent = AdminDepartment.query.get(parent_id)
                    if not parent:
                        return False
                    if parent.parent_id == current_id:
                        return True
                    if parent.parent_id is None:
                        return False
                    return is_child_department(parent.parent_id, current_id)

                if is_child_department(parent_id, id):
                    flash('不能将部门设置为其子部门的子部门', 'danger')
                    return render_template('admin/admin/admin_department_form.html', form=form, department=department)

            # 检查部门名称唯一性
            existing_department = AdminDepartment.query.filter(
                AdminDepartment.name == form.name.data,
                AdminDepartment.id != id
            ).first()

            if existing_department:
                flash('部门名称已存在', 'danger')
                return render_template('admin/admin/admin_department_form.html', form=form, department=department)

            department.name = form.name.data
            department.parent_id = form.parent_id.data if form.parent_id.data != 0 else None
            department.order_num = form.order_num.data
            department.wecom_id = form.wecom_id.data

            log = OperationLog(
                admin_id=current_user.id,
                action="编辑部门",
                resource="AdminDepartment",
                details=f"编辑部门: {form.name.data}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.add(log)
            db.session.commit()

            flash('部门已更新', 'success')
            return redirect(url_for('admin.admin_department.department_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'更新部门时出错: {str(e)}', 'danger')

    return render_template('admin/admin/admin_department_form.html',
                           form=form,
                           title='编辑部门',
                           department=department,
                           all_departments=all_departments)

@admin_department_bp.route('/departments/delete/<int:id>')
@login_required
def delete_department(id):
    department = AdminDepartment.query.get_or_404(id)

    if department.children.count() > 0:
        flash('无法删除有子部门的部门', 'danger')
        return redirect(url_for('admin.admin_department.department_management'))

    if AdminMember.query.filter_by(department_id=id).count() > 0:
        flash('无法删除有员工归属的部门', 'danger')
        return redirect(url_for('admin.admin_department.department_management'))

    try:
        db.session.delete(department)

        log = OperationLog(
            admin_id=current_user.id,
            action="删除部门",
            resource="AdminDepartment",
            details=f"删除部门: {department.name}",
            success=True,
            ip_address=request.remote_addr
        )
        db.session.add(log)
        db.session.commit()

        flash('部门已删除', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除部门时出错: {str(e)}', 'danger')

    return redirect(url_for('admin.admin_department.department_management'))